package com.seari.custody.service.Impl;

import cn.hutool.core.io.FileUtil;
import com.deepoove.poi.data.ParagraphRenderData;
import com.deepoove.poi.data.Paragraphs;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.Texts;
import com.deepoove.poi.data.style.ParagraphStyle;
import com.google.api.client.util.ArrayMap;
import com.seari.custody.bean.*;
import com.seari.custody.component.MinIoProperties;
import com.seari.custody.component.MinIoUtil;
import com.seari.custody.exception.BIZException;
import com.seari.custody.mapper.ReportProjectMapper;
import com.seari.custody.mapper.TechnicalAdviceMapper;
import com.seari.custody.mapper.TechnicalAuditOpinionMapper;
import com.seari.custody.service.TechnicalAdviceService;
import com.seari.custody.util.Common;
import com.seari.custody.util.HttpClientUtil;
import com.seari.custody.util.JwtTokenUtils;
import com.seari.custody.util.UUIDUtils;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("TechnicalAdviceService")
@Transactional(rollbackFor = Exception.class)
public class TechnicalAdviceServiceImpl implements TechnicalAdviceService {

    Object object = new Object();
    @Value("${minio.word}")
    private String minioword;
    @Value("${minio.pdf}")
    private String miniopdf;
    @Value("${minio.projectotherattach.bucket}")
    private String projectotherattach;
    @Value("${minio.url}")
    private String url;
    @Value("${record.url}")
    private String recordUrl;//档案系统下载接口地址
    @Value("${minio.fileAddress}")
    private String fileAddress;
    @Value("${minio.projectaccessory}")
    private String projectaccessory;
    @Value("${minio.projectword.bucket}")
    private String projectword;
    @Value("${minio.projectpdf.bucket}")
    private String projectpdf;
    @Autowired
    private TechnicalAdviceMapper technicalAdviceMapper;

    @Autowired
    private SpecialProtectionServiceImpl specialProtectionServiceImpl;

    @Autowired
    private ReportProjectMapper reportProjectMapper;

    @Autowired
    private MinIoUtil minIoUtil;

    @Autowired
    private TechnicalAuditOpinionMapper technicalAuditOpinionMapper;


    @Override
    public Map<String, Object> technicalReviewcreate(Map<String, String> map) throws Exception {
        String token = map.get("token");
        String uuid = map.get("uuid");
        // 类型
        String reviewType = map.get("reviewType");
        Map<String, Object> map1 = new HashMap<>();
        Date date = new Date();
        // token为空的情况下
        if (StringUtils.isNotEmpty(token) == false || token.equals("Bearer")) {
            map1.put("code", "500");
            map1.put("message", "token为空生成失败");
            map1.put("type", "fail");
            return map1;
        }
        // 生成用户名
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        Map<String, String> map2 = new HashMap<>();
        map2.put("uuid", uuid);
        Map<String, Object> stringObjectMap = technicalAdviceMapper.engineeringInformation(map2);
        // 工程信息——项目名称
        String project_name = (String) stringObjectMap.get("project_name");
        String deed = Common.specialCharacter(project_name);
        // 工程信息——流程状态
        String flowStatus = (String) stringObjectMap.get("flow_status");
        if (Integer.parseInt(flowStatus) >= 4) {
            map1.put("code", "500");
            map1.put("message", "待办状态有误");
            map1.put("type", "fail");
            return map1;

        }
        map.put("name", deed);
        // 查询工程信息是否为docx文件
        TechnicalFile technicalFile = new TechnicalFile();
        technicalFile.setProjectUuid(uuid);
        TechnicalFile list = technicalAdviceMapper.getServieFile(technicalFile);
        if (list == null) {
            map1.put("code", "500");
            map1.put("message", "工程信息概括为doc文件不符合要求,请修改为docx格式后重新提交");
            map1.put("type", "fail");
            return map1;
        }
        String filename = list.getFileName();
        map.put("filename", filename);
        // 许可类
        if (reviewType.equals("1")) {
            // 许可-生成技审意见逻辑
            technicalRevieLogic(map);
            // 分列展示
            Map<String, String> Agenda = new HashMap<>();
            Agenda.put("fileUuid", uuid);
            Agenda.put("technicalReviewtype", reviewType);
            List<TemplateWord> dee = selectAgenda(Agenda);
            map1.put("code", "200");
            map1.put("message", "生成许可类技审意见成功");
            map1.put("type", "success");
            map1.put("data", dee);
        }
        // 征询类
        if (reviewType.equals("2")) {
            //征询-生成技审意见逻辑
            selectConsult(map);
            // 分列展示
            Map<String, String> Agenda = new HashMap<>();
            Agenda.put("fileUuid", uuid);
            Agenda.put("technicalReviewtype", reviewType);
            List<TemplateWord> dee = selectAgenda(Agenda);
            map1.put("code", "200");
            map1.put("message", "生成征询类技审意见成功");
            map1.put("type", "success");
            map1.put("data", dee);
        }
        //更改流程状态
        if ("1".equals(flowStatus)) {
            technicalAdviceMapper.updateEngineeringLacerationStatus("3", uuid);
        }
        Map<String, Object> stringIntegerMap = reportProjectMapper.saverFileNumber(uuid);
        Integer flow_number = Integer.valueOf(stringIntegerMap.get("flow_number").toString());
        // 历史记录
        TechnicalHistory technicalHistory = new TechnicalHistory();
        technicalHistory.setCreateTime(date);
        technicalHistory.setOperationalType("1");
        technicalHistory.setOperationalFlow("3");
        technicalHistory.setOperationalContext(project_name + "技审意见生成");
        technicalHistory.setOperationalOperator(userNumber);
        technicalHistory.setOperationalState("1");
        technicalHistory.setOperationalProject(uuid);
        technicalHistory.setOperationalNumber(flow_number);
        technicalAdviceMapper.serverTechnicalHistory(technicalHistory);
        return map1;
    }




    @Override
    public void technicalRevieLogic(Map<String, String> map) throws Exception {
        Map<String, Object> params = new HashMap<>();
        Common common = new Common();
        Date date = new Date();
        String fileI = UUIDUtils.getUUID();
        String type = map.get("type");
        String uuid = map.get("uuid");
        String name = map.get("name");
        // 是否为管线
        String pipeline = map.get("pipeline");
        // 管线的类别
        String pipelinesort = map.get("pipelinesort");
        // 文件名称
        String filename = map.get("filename");
        // 模板中numtext设置为num自定义
        params.put("numtext", "{{num}}");

        // 获取项目的工程信息概况的url地址
        String url = minioword + filename;
        List<String> listed = new ArrayList<>();
        // 生成存储文件夹
        Common.createDir(fileAddress);
        TechnicalAdvice ta = common.finaled(projectword,filename);
        // 获取word中的图片信息。并以list表示
        List<String> documentimages = Common.documentimages(projectword,filename);
        // 对图片进行排序
        Collections.sort(documentimages, Comparator.comparingInt(o -> Integer.parseInt(o.replaceAll("[^0-9]*", ""))));
        ta.setFileUuid(uuid);
        ta.setFileId(fileI);
        ta.setCreateTime(date);
        List<Map<String, Object>> list1 = new ArrayList<>();
        List<Map<String, Object>> list2 = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String datemin = Common.uppercase(df.format(new Date()));
        // 获取图片信息
        for (int i = 0; i < documentimages.size(); i++) {
            Map<String, Object> datas = new HashMap<>();
            int num = i + 1;
            datas.put("tupianxx", "附图" + num + ":");
            datas.put("datemin", new PictureRenderData(600, 700, documentimages.get(i)));
            list1.add(datas);
        }
        // 存储图片信息
        params.put("animals", list1);
        // 存储word表格数据
        String excel = Common.WordExce(projectword,filename);
        // 工程概况
        String projectprofile;
        // 地铁结构
        String front1 = null;
        // A1 日期 设置日期格式
        params.put("datemin", datemin);
        // 地铁结构
        String dtjg = ta.getSubwayStructure();
        Integer indexOf1;
        if (dtjg == null || dtjg.length() == 0) {
            indexOf1 = -1;
        } else {
            indexOf1 = dtjg.indexOf("号线");
        }
        if (indexOf1 == -1) {
            params.put("number", "?");
        } else {
            // 获取关键字 number
            String front = Common.getNumeric(dtjg.substring((indexOf1 - 3), indexOf1));
            params.put("number", (front.length() == 0) ? "?" : Common.zerofill(front));
        }
        // 建设单位
        params.put("development", ta.getConstructionUnit());
        // 项目名称
        params.put("projectname", ta.getProjectName());
        // 工程概况、地铁结构
        projectprofile = ta.getProjectOverview();
        params.put("projectprofile", projectprofile);
        // 地铁结构
        params.put("projectpromain", excel);
        // 相对位置关系
        params.put("relativelocation", ta.getRelativeLocation());
        String realPath = "";
        File realfile = null;
        // 1、基坑类模板
        switch (type) {
            case "1":
                // A7建筑物基础
                params.put("buildingfoundation", ta.getBuildingfoundation());
                // A8分区施工和工程进度要求
                params.put("subdivisionconstruction", ta.getSubdivisionconstruction());
                // A9基坑围护
                params.put("containment", ta.getContainment());
                // A10地基加固
                params.put("groundStabilization", ta.getGroundStabilization());
                // A11支撑体系
                params.put("supportSystem", ta.getSupportSystem());
                // A12降水问题
                params.put("precipitationProblems", ta.getPrecipitationProblems());
                 realfile = com.seari.custody.util.FileUtil.copyResourceFileToTemp("patternplate\\技审意见\\基坑类\\技审意见模板基坑类.docx");
//                realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\patternplate\\技审意见\\基坑类\\技审意见模板基坑类.docx";
                listed = common.downloadWord(realfile, params, name + "许可基坑技审意见");
                break;
            case "2":
                 realfile = com.seari.custody.util.FileUtil.copyResourceFileToTemp("patternplate\\技审意见\\拆除类\\技审意见模板拆除类.docx");
//                realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\patternplate\\技审意见\\拆除类\\技审意见模板拆除类.docx";
                listed = common.downloadWord(realfile, params, name + "许可类拆除技审意见");
                break;
            case "3":
                realfile = com.seari.custody.util.FileUtil.copyResourceFileToTemp("patternplate\\技审意见\\勘探类\\技审意见模板勘察类.docx");
//                realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\patternplate\\技审意见\\勘探类\\技审意见模板勘察类.docx";
                listed = common.downloadWord(realfile, params, name + "许可类勘察技审意见");
                break;
            case "4":
                // 绿化换填方案
                realfile = com.seari.custody.util.FileUtil.copyResourceFileToTemp("patternplate\\技审意见\\绿化类\\技审意见模板绿化类.docx");
                params.put("greeningfill", ta.getGreeningfill());
//                realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\patternplate\\技审意见\\绿化类\\技审意见模板绿化类.docx";
                listed = common.downloadWord(realfile, params, name + "许可类绿化技审意见");
                break;
            case "5":
                // 对市政类相对关系进行渲染
                List<Map<String, Object>> shizheng = common.RelativePositionRelation(projectword,filename, "相对位置关系", "设计单位（盖章）");
                params.put("directory", shizheng);

                String section = map.get("section");
                System.out.println("section的值：" + section);
                if (section.contains("4")) {
                    // 渲染文本
                    ParagraphStyle paragraphStyle = ParagraphStyle.builder().build();
                    params.put("elevated", "高架要求");
                    ParagraphRenderData para = Paragraphs.of("（1）加卸载要求"
                            + "\n\t\t" + "高架桥立柱结构外边线1m范围内原则不进行任何建筑施工，禁止在桥梁墩柱附近新增附加荷载超过1T/m2，高架立柱周围应设置半封闭混凝土挡墙等防护措施，根据安全保护区规定施工距离应超过3m，设计单位应进一步深化调整设计，高架立柱周围设隔离带并立警示牌。关键问题做好永久性防护，避免机动车撞击地铁结构问题。"
                            + "\n" + "（2）道路下穿高架"
                            + "\n\t\t" + "道路在桩号")
                            .addText(Texts.of("XXX~XXX").color("FF0000").bold().create())
                            .addText("段下穿轨道交通")
                            .addText(Texts.of("XXX").color("FF0000").bold().create())
                            .addText("号线和进出场线，横向道路在轨道交通高架段下方穿行区域，应注意路面标高设计，充分考虑各类车辆的通行条件，要求在地铁桥梁两侧设置限高措施，以保证桥梁安全。目前设计道路路面至高架桥梁底净距")
                            .addText(Texts.of("XXXm").color("FF0000").bold().create())
                            .addText("，要求在罗山路及前一个交叉口提前设置4.5m限高装置以保护轨交高架桥梁。" + "\n\t\t" + "轨道交通设计地面标高约")
                            .addText(Texts.of("XXXm").color("FF0000").bold().create())
                            .addText(Texts.of("XXXm").color("FF0000").bold().create())
                            .addText("，竣工后地面标高")
                            .addText(Texts.of("XXX~XXXm").color("FF0000").bold().create())
                            .addText("，高架投影范围最大挖方高度约")
                            .addText(Texts.of("XXm").color("FF0000").bold().create())
                            .addText("，设置U型槽下穿轨交结构。下穿通道为双向六车道分离式U型钢筋砼结构，结构宽")
                            .addText(Texts.of("XXm").color("FF0000").bold().create())
                            .addText("，里程")
                            .addText(Texts.of("XXX~XXX").color("FF0000").bold().create())
                            .addText("采用明挖施工，围护结构采用1:1.5放坡处理，坑底以下3m采用D850@600三重管高压旋喷桩抽条加固。" + "\t\t")
                            .paraStyle(paragraphStyle).create();
                    params.put("elevatedone", para);
                } else {
                    ParagraphStyle paragraphStyle = ParagraphStyle.builder().build();
                    System.out.println("不包含隧道信息");
                    params.put("elevated", "隧道要求");
                    ParagraphRenderData para = Paragraphs.of("卸载及换填要求：轨道交通结构正上方及其外边线两侧各一倍结构底埋深范围内禁止新增任何附加荷载，要求对此范围内标高改变低于0.5m的区域可采用轻质泡沫混凝土，超0.5m的区域采用EPS/轻质材料换填。如桥接坡段抬高高度超过1.5m应考虑桩基基础。").paraStyle(paragraphStyle).create();
                    params.put("elevatedone", para);
                }
                // 是否为管线
                if ("1".equals(pipeline)) {
                    List<String> pipe = Arrays.asList(pipelinesort.split(","));
                    params.put("pipeline", "4.6管线工程");
                    params.put("pipelinetext","\t"+"雨水管道采用DN600～1000管道，污水管道采用DN400接至已建市政污水总管。雨水管采用承插式钢筋砼管、承插式双壁波纹管（HDPE），污水管采用HDPE、PE100级平壁热熔牵引管；燃气管拟排D219*8中压高频直缝电阻焊钢管。管线普遍采用开槽埋管施工，污水管穿越泗陈公路段采用拖拉管施工。" +"\n"+"\t" + "管节本身防水和接头防水是系统防水关键，管道本身及接头应具备较大差异沉降能力和防水性能。地铁保护区范围内永久性管道的防水应予以重点考虑，以减少管道渗漏水对地铁结构的影响。原则上接头应具备较大差异沉降能力和防水性能。如在使用期间发生管道渗漏影响地铁结构安全，建设单位必须采取补救措施，并承担相关的费用。");
                    for (int i = 0; i < pipe.size(); i++) {
                        Map<String, Object> datas = new HashMap<>();
                        if (pipe.get(i).equals("1")) {
                            datas.put("biaottixx", "4.6." + (i + 1) + "开槽埋管施工");
                            datas.put("biaottixxtext", "污水管沟槽开挖深度大于3m采用4～6m钢板桩围护，沟槽应分段开挖并及时支撑，分段快速设置管段。单段长度一般不超过6m，沟槽的“开挖、埋管、回填”施工时间不应超过6小时。过车站段挖深要求至少距顶板防水层50cm，人工开挖，车站结构上方管线开挖前需做样沟，不得破坏车站结构顶板防水。如施工过程中遇到障碍物应立即停工，开挖施工过程中如遇异常，需及时与地铁监护部门联系。部分管线施工距离出入口较近,应避开早、晚高峰期，注意对出入口的安全防护。做好防烟、防尘、防震等保护措施，不得影响乘客正常出行。地铁夜间停运后实施，开挖施工过程中如遇异常，需及时与地铁单位联系。");
                        }
                        if (pipe.get(i).equals("2")) {
                            datas.put("biaottixx", "4.6." + (i + 1) + "拖拉管施工");
                            datas.put("biaottixxtext", "导向孔钻进过程须严格控制线路误差，扩孔过程须保证泥浆护壁稳定性。回拖完毕后的管体与孔壁之间缝隙应压浆填充密实控制。在导向孔及后期拖管的过程中，施工单位应始终保持设备的完好，防止设备故障发生后重新钻进时对隧道结构变形过大，影响地铁安全。拖拉管施工过程中须严格控制与隧道之间的距离。"
                                    + "\n\t\t" + "施工单位须向地铁监护人员提供一套稳定的拖拉施工参数，视施工对区间结构影响大小调整施工参数,确保施工顺利安全。");

                        }
                        if (pipe.get(i).equals("3")) {
                            datas.put("biaottixx", "4.6." + (i + 1) + "顶管施工");
                            datas.put("biaottixxtext", "在顶管穿越段位置到达前，施工单位须向地铁监护人员提供一套稳定的施工参数。主要施工参数包括顶管的推进、纠偏、正面土压力等，根据对环境影响情况，调整施工参数，确保施工顺利安全。具体要求如下："
                                    + "\n\t\t" + "(1)、顶管顶进速度。顶进须均匀、慢速、稳定地顶进，严格控制在≤10mm/min，推进10cm停机10～30mins，停机时间视顶进对地铁结构的影响而确定。"
                                    + "\n\t\t" + "(2)、顶管纠偏。严格实施小幅度纠偏以控制施工对地铁结构的影响，每顶进10cm实施一次纠偏，杜绝单次大幅度纠偏。"
                                    + "\n\t\t" + "(3)、顶管正面压力。顶进压力应视监测数据进行调整。"
                                    + "\n\t\t" + "其他要求："
                                    + "\n\t\t\t" + "(1)、顶管施工结束"
                                    + "\n\t\t" + "施工以后，对于顶管顶端及时用迟凝泥浆置换原有的触变浆液。置换的泥浆采用纯水泥浆进行置换。利用压注触变泥浆的系统及管路进行置换。率先对该区域进行泥浆置换施工，首先进行测量，确定该区域管节位置，然后依次进行泥浆置换。"
                                    + "\n\t\t\t" + "(2)、顶管距××号线地铁结构较近，该段隧道已形成，（视情况）电力电缆隧道应考虑减小相互干扰措施以及隧道渗漏等病害处置预留措施。"
                                    + "\n\t\t\t" + "(3)、顶管推进过程中及工程投入使用后，如发现因项目实施而引起地铁结构变形过大或结构损伤，建设单位须按上海申通地铁集团有限公司根据新情况提出的要求对地铁实施加固处理措施，并承担相应法律责任。"
                            );
                        }
                        if (pipe.get(i).equals("4")) {
                            datas.put("biaottixx", "4.6." + (i + 1) + "工作井围护设计");
                            datas.put("biaottixxtext",
                                    "\t\t" + "(1)、工作井围护及支撑"
                                            + "\n\t\t" + "围护结构采用φ850三轴搅拌桩+H型钢，桩长19m。距高架桥墩12m范围内型钢禁止拔出。支撑采用对撑+角撑平面形式，竖向设三道支撑，首道为钢筋混凝土支撑，其它为钢支撑。"
                                            + "\n\t\t" + "(2)、工作井加固"
                                            + "\n\t\t" + "接收井坑内采用三轴搅拌桩满堂加固，加固深度自第二道支撑底至坑底以下4m。接收井坑外顶管接收侧加固采用三轴搅拌桩加固，加固宽度11m，加固长度3m，加固深度6m。要求强加固区水泥掺量不小于20%。注意加固体的搭接可靠和压力可控，既要满足搭接要求，又要降低施工扰动。"
                            );
                        }
                        list2.add(datas);
                    }
                    params.put("animalsed", list2);
                    realfile = com.seari.custody.util.FileUtil.copyResourceFileToTemp("patternplate\\技审意见\\市政类\\技审意见模板市政类—管线.docx");
//                    realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\patternplate\\技审意见\\市政类\\技审意见模板市政类—管线.docx";
                    listed = common.downloadWord(realfile, params, name + "许可管线市政类技审意见");

                } else {
                    realfile = com.seari.custody.util.FileUtil.copyResourceFileToTemp("patternplate\\技审意见\\市政类\\技审意见模板市政类—非管线.docx");
//                    realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\patternplate\\技审意见\\市政类\\技审意见模板市政类—非管线.docx";
                    listed = common.downloadWord(realfile, params, name + "许可非管线市政类技审意见");
                }
                break;
            case "6":
                // 对穿越类相对关系进行渲染
                List<Map<String, Object>> shizhengThrough = common.ThroughRelativePositionRelation(projectword,filename, "相对位置关系", "设计单位（盖章）");
                params.put("directory", shizhengThrough);
//                realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\patternplate\\技审意见\\穿越类\\技审意见模板穿越类.docx";
                realfile = com.seari.custody.util.FileUtil.copyResourceFileToTemp("patternplate\\技审意见\\穿越类\\技审意见模板穿越类.docx");
                listed = common.downloadWord(realfile, params, name + "许可类穿越技审意见");
                break;
            default:

        }
        FileUtil.del(realfile);
        // WORD文件地址
        String filePath = listed.get(0);
        // WORD文件名
        String fileName = listed.get(1);
        File fileed = new File(filePath);
        ta.setFileName(fileName);
        FileInputStream fileInputStream = new FileInputStream(fileed);
        String contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        minIoUtil.putObject("projectword", fileName, fileInputStream, contentType);
        List<String> listeded = common.doc2pdf(filePath, name + "技审意见");
        //生成pdf文件地址
        String pdfread = listeded.get(0);
        //生成pdf文件名称
        String pdfname = listeded.get(1);
        File fileed1 = new File(pdfread);
        FileInputStream fileInputStream1 = new FileInputStream(fileed1);
        String contentType1 = "application/pdf";
        minIoUtil.putObject("projectpdf", pdfname, fileInputStream1, contentType1);
        ta.setPdfName(pdfname);
        // 工程概括、地铁结构组合
        String InformationOverview = projectprofile + "," + excel;
        ta.setUploadingType(type);
        ta.setInformationOverview(InformationOverview);
        ta.setUploadingId("0");
        // 1、许可类
        ta.setTechnicalReviewtype("1");
        // 当生成技审状态为市政类时添加加入是否为管线和管线内容
        if ("5".equals(type)) {
            ta.setPipeline(map.get("pipeline"));
            ta.setPipelinesort(map.get("pipelinesort"));
        }
        technicalAdviceMapper.saverOverview(ta);
        // IO流关闭
        fileInputStream.close();
        fileInputStream1.close();
        TemplateWord tam = new TemplateWord();
        tam.setFileUuid(uuid);
       
    }

    @Override
    public List<TemplateWord> selectAgenda(Map<String, String> map) throws Exception {
        List<TemplateWord> ma = technicalAdviceMapper.techcaladviceList(map);
        for (TemplateWord templateWord : ma) {
            //Word文件名
            String a = templateWord.getFileName();
            StringBuilder builder1 = new StringBuilder();
            builder1.append(minioword).append(a);
            //拼接minio的word的url地址
            templateWord.setFileName(builder1.toString());
            //拼接minio的pdf的url地址
            String b = templateWord.getPdfName();
            StringBuilder builder2 = new StringBuilder();
            builder2.append(miniopdf).append(b);
            templateWord.setPdfName(builder2.toString());
        }
        return ma;
    }


    @Override
    public void selectConsult(Map<String, String> map) throws Exception {
        String name = map.get("name");
        Map<String, Object> params = new HashMap<>();
        String fileI = UUIDUtils.getUUID();
        String type = "1";
        String uuid = map.get("uuid");
        System.out.println("uuid" + uuid);
        params.put("numtext", "{{num}}");
        TechnicalFile file = new TechnicalFile();
        file.setProjectUuid(uuid);
        Common common = new Common();
        TechnicalFile list = technicalAdviceMapper.getServieFile(file);
        String id = list.getId();
        String filename = list.getFileName();
        //获取项目的工程信息概况的url地址
        String url = minioword + filename;
        Date date = new Date();
        List<String> listed = new ArrayList<>();
        //生成存储文件夹
        Common.createDir(fileAddress);
        TechnicalAdvice ta = common.finaled(projectword,filename);
        //获取word中的图片信息。并以list表示
        List<String> documentimages = Common.documentimages(projectword,filename);
        ta.setFileUuid(uuid);
        ta.setFileId(fileI);
        ta.setCreateTime(date);
        List<Map<String, Object>> list1 = new ArrayList<>();
        List<Map<String, Object>> list2 = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String datemin = Common.uppercase(df.format(new Date()));
        //获取图片信息
        for (int i = 0; i < documentimages.size(); i++) {
            Map<String, Object> datas = new HashMap<>();
            int num = i + 1;
            datas.put("tupianxx", "附图" + num + ":");
            datas.put("datemin", new PictureRenderData(600, 700, documentimages.get(i)));
            list1.add(datas);
        }
        //存储图片信息
        params.put("animals", list1);
        //存储word表格数据
        String excel = Common.WordExce(projectword,filename);
        //工程概况
        String projectprofile;
        //地铁结构
        String front1 = null;
        //A1 日期 设置日期格式
        params.put("datemin", datemin);
        //地铁结构
        String dtjg = ta.getSubwayStructure();
        Integer indexOf1;
        if (dtjg == null || dtjg.length() == 0) {
            indexOf1 = -1;
        } else {
            indexOf1 = dtjg.indexOf("号线");
        }
        if (indexOf1 == -1) {
            params.put("number", "?");
        } else {
            //获取关键字 number
            String front = Common.getNumeric(dtjg.substring((indexOf1 - 3), indexOf1));
            params.put("number", Common.zerofill(front));
        }
        //建设单位
        params.put("development", ta.getConstructionUnit());
        //项目名称
        params.put("projectname", ta.getProjectName());
        //工程概况、地铁结构
        projectprofile = ta.getProjectOverview();
        params.put("projectprofile", projectprofile);
        //地铁结构
        params.put("projectpromain", excel);
        //相对位置关系
        params.put("relativelocation", ta.getRelativeLocation());

//        String realPath = System.getProperty("user.dir") + "\\src\\main\\resources\\patternplate\\技审意见\\征询类\\征询技审意见建筑类.docx";
        File realfile = com.seari.custody.util.FileUtil.copyResourceFileToTemp("patternplate\\技审意见\\征询类\\征询技审意见建筑类.docx");
        listed = common.downloadWord(realfile, params, name + "征询类建筑技审意见");
        //WORD文件地址
        String filePath = listed.get(0);
        //WORD文件名
        String fileName = listed.get(1);
        File fileed = new File(filePath);
        ta.setFileName(fileName);
        FileInputStream fileInputStream = new FileInputStream(fileed);
        String contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        minIoUtil.putObject("projectword", fileName, fileInputStream, contentType);
        List<String> listeded = common.doc2pdf(filePath, name + "征询技审意见");
        //生成pdf文件地址
        String pdfread = listeded.get(0);
        //生成pdf文件名称
        String pdfname = listeded.get(1);
        File fileed1 = new File(pdfread);
        FileInputStream fileInputStream1 = new FileInputStream(fileed1);
        String contentType1 = "application/pdf";
        minIoUtil.putObject("projectpdf", pdfname, fileInputStream1, contentType1);
        ta.setPdfName(pdfname);
        //工程概括、地铁结构组合
        String InformationOverview = projectprofile + "项目" + excel;
        ta.setUploadingType(type);
        ta.setInformationOverview(InformationOverview);
        //0用户上传
        ta.setUploadingId("0");
        //2征询类
        ta.setTechnicalReviewtype("2");
        technicalAdviceMapper.saverOverview(ta);
        //IO流关闭
        fileInputStream.close();
        fileInputStream1.close();
    }


    @Override
    public Integer saverOverview(TechnicalAdvice mf) {
        return technicalAdviceMapper.saverOverview(mf);
    }


    @Override
    public TechnicalFile getServieFile(TechnicalFile file) {

        return technicalAdviceMapper.getServieFile(file);
    }


    @Override
    public List<TechnicalType> technicalType() {
        return technicalAdviceMapper.technicalType();
    }

    /**
     * 许可类上传技审草稿退回分：
     * 0未退回 1已退回  2已解决
     *
     * @param map 实体类的数据
     * @return
     */
    @Override
    public List<TemplateWord> technicalListed(Map<String, String> map) {
        List<TemplateWord> ta = technicalAdviceMapper.technicalListed(map);
        String uuid = map.get("uuid");
        String type = "";
        for (TemplateWord templateWord : ta) {
            //Word文件名
            String a = templateWord.getFileName();
            String aa = minioword + a;
            templateWord.setFileName(aa);
            //pdf文件名
            String b = templateWord.getPdfName();
            String bb = miniopdf + b;
            templateWord.setPdfName(bb);

            //退回状态
            String sendBack = templateWord.getReturnedState();
            //已退回
            if ("1".equals(sendBack)) {
                type = "1";
                break;
            }
        }
        if ("1".equals(type)) {
            map.put("returnedState", "1");
            List<TemplateWord> ta1 = technicalAdviceMapper.technicalbsBackspacing(map);
            for (TemplateWord templateWord : ta1) {
                //Word文件名
                String a = templateWord.getFileName();
                String aa = minioword + a;
                templateWord.setFileName(aa);
                //pdf文件名
                String b = templateWord.getPdfName();
                String bb = miniopdf + b;
                templateWord.setPdfName(bb);
            }
            return ta1;
        } else {
            return ta;
        }


    }

    @Override
    public List<TemplateWord> consultList(Map<String, String> map) {
        List<TemplateWord> ta = technicalAdviceMapper.consultList(map);
        for (TemplateWord templateWord : ta) {
            //Word文件名
            String a = templateWord.getFileName();
            String aa = minioword + a;
            templateWord.setFileName(aa);
            //pdf文件名
            String b = templateWord.getPdfName();
            String bb = miniopdf + b;
            templateWord.setPdfName(bb);
        }
        return ta;
    }

    @Override
    public List<TemplateWord> technicalbsBackspacing(Map<String, String> map) {
        return technicalAdviceMapper.technicalbsBackspacing(map);
    }


    @Override
    public Map<String, String> uploadstatus(MultipartFile files, String uuid, String reviewType) throws Exception {
        Map<String, String> draftlast = new HashMap<>();
        // 判断是否已上传
        String flowStatus = technicalAdviceMapper.engineeringLacerationStatus(uuid);
        if (!("3".equals(flowStatus)||"5".equals(flowStatus))) {
            draftlast.put("code", "500");
            draftlast.put("message", "技审:待办状态有误");
            return draftlast;
        }

        String fileI = UUIDUtils.getUUID();
        MultipartFile file = files;
        SimpleDateFormat impleDateFormat = new SimpleDateFormat("HHmm");//设置日期格式
        long time = Long.parseLong(impleDateFormat.format(new Date()));
        InputStream is = file.getInputStream(); //得到文件流
        String fileName = file.getOriginalFilename(); //文件名
        String contentType = file.getContentType();  //类型
        //获取文件后缀名
        int begin = file.getOriginalFilename().indexOf(".");
        //获得文件名
        String a = file.getOriginalFilename().substring(0, begin);
        String b = Common.specialCharacter(a);
        String ab = b + time + ".docx";
        String abpdf = b + time;
        // 下载文件到本地
        Common.approvalFile(file);
        String mimi = fileAddress + fileName;
        Integer techniCalnum = technicalAdviceMapper.technicalnum(uuid);
        int abc;
        // 上传word文件更换num值
        if (techniCalnum == null || techniCalnum == 0) {
            String amb = technicalAdviceMapper.numtextSum();
            Integer numtextSum = 0;
            if (amb == null) {
                numtextSum = 0;
            } else {
                numtextSum = Integer.parseInt(amb);
            }
            abc = numtextSum + 1;
        } else {
            //如编号值存在则
            abc = techniCalnum;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("num", Common.zerofill(String.valueOf(abc)));
        Common common = new Common();
        List<String> listed = common.downloadWord(mimi, params, "上传文件");
        // 新生成WORD文件本地地址
        String filePath = listed.get(0);
        FileInputStream fileInputStream = new FileInputStream(new File(filePath));
        // 上传到minio目录
        minIoUtil.putObject("projectword", ab, fileInputStream, contentType);
        // 获取文件上传的路径
        List<String> listeded = common.makenpdf(filePath, abpdf);
        // 生成pdf文件地址
        String pdfread = listeded.get(0);
        // 生成pdf文件名称
        String pdfname = listeded.get(1);
        FileInputStream fileInputStream1 = new FileInputStream(new File(pdfread));
        String contentType1 = "application/pdf";
        minIoUtil.putObject("projectpdf", pdfname, fileInputStream1, contentType1);
        //读取信息概况文件
        TechnicalFile technifile = new TechnicalFile();
        technifile.setProjectUuid(uuid);
        TechnicalFile list = technicalAdviceMapper.getServieFile(technifile);
        String id = list.getId();
        String file_name = list.getFileName();
        String url = minioword + id + file_name;
        //读取表格
        TechnicalAdvice ta = new TechnicalAdvice();
        //工程概括、地铁结构组合
        Date date = new Date();
        //获取最新的word文档的类型
        String techninum = technicalAdviceMapper.reviewopinion(uuid);
        // 上传生成编号的word文件到minio服务器
        String fileurl = minioword + ab;
        // word桶名  word文件名  档案系统下载编号
        String fileId = HttpClientUtil.uploadFilePdf(projectword, ab, "57");
        // pdf桶名  pdf文件名 档案系统下载编号
        String filepdf = HttpClientUtil.uploadFilePdf(projectpdf, pdfname, "57");
        if(fileId.equals("0")||filepdf.equals("0")){
            draftlast.put("code", "500");
            draftlast.put("message", "档案系统:档案系统异常");
            return draftlast;
        }

        ta.setFileUuid(uuid);
        ta.setFileName(ab);
        ta.setPdfName(pdfname);
        ta.setFileId(fileI);
        ta.setUploadingId("1");
        ta.setCreateTime(date);
        ta.setUploadingType(techninum);
        ta.setFileSystemId(fileId);
        ta.setFileSystpdf(filepdf);
        if (reviewType.equals("1")) {
            ta.setTechnicalReviewtype("1");
        } else {
            ta.setTechnicalReviewtype("2");
        }
        ta.setNumtext(String.valueOf(abc));
        technicalAdviceMapper.saverOverview(ta);
        is.close();
        fileInputStream.close();
        fileInputStream1.close();
        //生成专项保护方案的数据
        Map<String, String> maped = new HashMap<>();
        maped.put("type", techninum);
        maped.put("uuid", uuid);
        maped.put("tnical", fileI);
        maped.put("name", abpdf);
        //许可类生成专项保护方案
        if (reviewType.equals("1")) {
            // 生成专项保护方案
            String bb = specialProtectionServiceImpl.SpecialProtectionType(maped);
            if (bb.equals("上传技审文件成功")) {
                draftlast.put("code", "200");
                draftlast.put("message", bb);
                Map<String, String> map2 = new HashMap<>();
                map2.put("uuid", uuid);
                Map<String, Object> engineeringInformation = technicalAdviceMapper.engineeringInformation(map2);
                //项目编号
                String no = engineeringInformation.get("no").toString();
                //项目类型
                String type = engineeringInformation.get("type").toString();
                //项目所属人员工号
                String manager_number = engineeringInformation.get("manager_number").toString();
                //2、技审草稿文件——回传数据到报审系统
                Map<String, String> report = new HashMap<>();
                report.put("no", no);
                report.put("fileId", fileId);
                report.put("fileName", ab);
                report.put("fileType", "word");
                report.put("personNumber", manager_number);
                report.put("type", type);
                report.put("UUID", fileI);
                Map<String, String> uploadedForReview = Common.uploadedForReview(report);
                String code = uploadedForReview.get("code");
                String message = uploadedForReview.get("message");
                Boolean booleaned = code.equals("200");
                if (booleaned) {
                    draftlast.put("code", "200");
                    draftlast.put("message", "上传技审文件成功");
                } else {
                    draftlast.put("code", "500");
                    draftlast.put("message", "报审:"+message);
                    return draftlast;
                }

            } else {
                draftlast.put("code", "500");
                draftlast.put("message", "技审:"+bb);
                return draftlast;
            }
        } else {
            draftlast.put("code", "200");
            draftlast.put("message", "技审草稿上传成功");
        }

        // 更改流程 当状态为：处理中、技审草稿被退回待处理时更改状态
        if (flowStatus.equals("3")||flowStatus.equals("5")) {
            technicalAdviceMapper.updateEngineeringLacerationStatus("4", uuid);
        }
        // 如有技审草稿退回上传,进行状态变更
        Map<String, String>  LatestPermits=new HashMap<>();
        LatestPermits.put("returned_state","2");
        LatestPermits.put("file_uuid",uuid);
        technicalAuditOpinionMapper.updateLatestSendBack(LatestPermits);
        //流程  许可|征询
        Map<String, Object> stringIntegerMap = reportProjectMapper.saverFileNumber(uuid);
        Integer flow_number = Integer.valueOf(stringIntegerMap.get("flow_number").toString());
        TechnicalHistory technicalHistory = new TechnicalHistory();
        technicalHistory.setCreateTime(new Date());
        technicalHistory.setOperationalType("1");
        technicalHistory.setOperationalFlow("4");
        technicalHistory.setOperationalContext("专项草稿审核");
        technicalHistory.setOperationalState("1");
        technicalHistory.setOperationalProject(uuid);
        technicalHistory.setOperationalNumber(flow_number);
        technicalAdviceMapper.serverTechnicalHistory(technicalHistory);
        return draftlast;
    }

    @Override
    public Integer adviceUpload(TechnicalAdvice tw) {
        return technicalAdviceMapper.adviceUpload(tw);
    }

    @Override
    public Integer accessoryupload(TechnicalAccessory ta) {
        return technicalAdviceMapper.accessoryupload(ta);
    }

    @Override
    public List<TemplateWord> templatId(TemplateWord ta) {
        return technicalAdviceMapper.templatId(ta);
    }

    @Override
    public Integer technicaldelect(String ta) {
        return technicalAdviceMapper.technicaldelect(ta);
    }

    @Override
    public List<TechnicalAccessory> getTechnicalAccessoryListByProjectUuid(String uuid) throws Exception {
        List<TechnicalAccessory> technicalAccessoryListByProjectUuid = technicalAdviceMapper.getTechnicalAccessoryListByProjectUuid(uuid);
        for (TechnicalAccessory t : technicalAccessoryListByProjectUuid) {
            t.setAessFullnam(projectaccessory + t.getAessName());
        }
        return technicalAccessoryListByProjectUuid;
    }

    @Override
    public Integer technicalnum(String fileuuid) {
        return technicalAdviceMapper.technicalnum(fileuuid);
    }

    @Override
    public void templatdelect(Map<String, String> map) throws Exception {
        String fileId = map.get("fileid");
        //获取token的用户名
        String userNumber = map.get("userNumber");
        //删除时的uuid
        String fileUuid = map.get("fileUuid");
        TechnicalAdvice technicalAdvice = technicalAdviceMapper.selectTechnicalAdviceByUuid(fileId);
        //获取技审上传类型
        String uploadingId = technicalAdvice.getUploadingId();
        //获取技审docx的值
        String docx = technicalAdvice.getFileName();
        //获取技审pdf的值
        String pdf = technicalAdvice.getPdfName();

        technicalAdviceMapper.technicaldelect(fileId);

        TechnicalHistory technicalHistory = new TechnicalHistory();
        Date date = new Date();

        //根据UUID 得到相应的工程信息状态
        Map<String, String> map1 = new HashMap<>();
        map1.put("uuid", fileUuid);
        Map<String, Object> stringObjectMap = technicalAdviceMapper.engineeringInformation(map1);
        // 技审意见状态
        String flow_status = (String) stringObjectMap.get("flow_status");
        Integer integer = technicalAdviceMapper.countTechnicalDraft(fileUuid);

        if (flow_status.equals("3") && integer == 0) {
            Map<String, String> map2 = new HashMap<>();
            map2.put("flowStatus", "1");
            map2.put("uuid", fileUuid);
            technicalAdviceMapper.updateFeedback(map2);
        }

        //用户上传为1 且需同时删除专项保护方案数据
        if (uploadingId.equals("1")) {
            List<Technicalzxlist> mn = technicalAdviceMapper.technicalzxfazxfalist(fileId);
            //读取专项保护方案word
            String WordName = mn.get(0).getWordName();
            //读取专项保护方案pdf
            String PdfName = mn.get(0).getPdfName();
            technicalAdviceMapper.specialdelect(fileId);

            //历史记录变更
            technicalHistory.setCreateTime(date);
            technicalHistory.setOperationalType("3");
            technicalHistory.setOperationalContext("技审意见上传删除");
            technicalHistory.setOperationalOperator(userNumber);
            technicalHistory.setOperationalState("1");
            technicalHistory.setOperationalProject(fileUuid);
            technicalAdviceMapper.serverTechnicalHistory(technicalHistory);


            Thread th = new Thread(() -> {
                try {
                    downtechnicalFile(docx, pdf);
                    downtechnicalFile(WordName, PdfName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            );
            th.start();
        } else {

            //历史记录变更
            technicalHistory.setCreateTime(date);
            technicalHistory.setOperationalType("3");
            technicalHistory.setOperationalContext("技审意见生成删除");
            technicalHistory.setOperationalOperator(userNumber);
            technicalHistory.setOperationalState("1");
            technicalHistory.setOperationalProject(fileUuid);
            technicalAdviceMapper.serverTechnicalHistory(technicalHistory);

            Thread th = new Thread(() -> {
                try {
                    downtechnicalFile(docx, pdf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            );
            th.start();
        }


    }

    @Override
    public Integer specialdelect(String no) {
        List<Technicalzxlist> mn = technicalAdviceMapper.technicalzxfazxfalist(no);
        //读取专项保护方案word
        String WordName = mn.get(0).getWordName();
        //读取专项保护方案pdf
        String PdfName = mn.get(0).getPdfName();
        technicalAdviceMapper.specialdelect(no);
        Thread th = new Thread(() -> {
            try {
                downtechnicalFile(WordName, PdfName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        );
        th.start();
        return technicalAdviceMapper.specialdelect(no);
    }

    @Override
    public String reviewopinion(String file_uuid) {
        return technicalAdviceMapper.reviewopinion(file_uuid);
    }

    @Override
    public String numtextSum() throws Exception {
        return technicalAdviceMapper.numtextSum();
    }

    @Override
    public List<TechnicalList> technicalzxfalist(String fileUuid) {
        List<TechnicalList> list = technicalAdviceMapper.technicalzxfalist(fileUuid);
        for (TechnicalList techni : list) {
            String a = techni.getFileName();
            String b = techni.getPdfName();
            int begin1 = a.indexOf(".");
            int begin2 = b.indexOf(".");
            String ab = a.substring(0, begin1);
            String bb = b.substring(0, begin2);
            techni.setFileName(ab);
            techni.setPdfName(bb);
        }
        return list;
    }

    @Override
    public List<Technicalzxlist> technicalzxfazxfalist(String no) {
        List<Technicalzxlist> list = technicalAdviceMapper.technicalzxfazxfalist(no);
        Integer num = 0;
        for (Technicalzxlist techni : list) {
            String a = techni.getWordName();
            String b = techni.getPdfName();
            int begin1 = a.indexOf(".");
            int begin2 = b.indexOf(".");
            String ab = a.substring(0, begin1);
            String bb = b.substring(0, begin2);
            techni.setWordName(ab);
            techni.setPdfName(bb);
        }
        return list;
    }

    @Override
    public String engineeringLacerationStatus(String uuid) {
        return technicalAdviceMapper.engineeringLacerationStatus(uuid);
    }

    @Override
    public long updateEngineeringLacerationStatus(String flowstatus, String uuid) {
        return technicalAdviceMapper.updateEngineeringLacerationStatus(flowstatus, uuid);
    }

    @Override
    public Integer wordIncludePic(MultipartFile files, String fileType) throws Exception {
        Common.approvalFile(files);
        String fileName = files.getOriginalFilename(); //文件名
        String dstImgFolder = fileAddress + fileName;
        if ("word".equals(fileType)) {
            //档案系统文件ID
            //获取word中的图片信息。并以list表示
            List<String> documentimages = Common.documentimagesed(dstImgFolder);
            if (documentimages.size() == 0) {
                return 1;
            } else if (documentimages.size() > 0) {
                return 2;
            } else {
                return 3;
            }
        } else if ("pdf".equals(fileType)) {
//            List list = Common.pdfParsing(dstImgFolder);
            List list = Common.pdfConversion(dstImgFolder, "C:\\mimi", 200);
            Integer list1 = Common.sealOfInformation(list);
            if (list1 == 1) {
                return 4;
            } else if (list1 == 0) {
                return 5;
            } else {
                return 6;
            }
        } else {
            return 0;
        }


    }

    @Override
    public Integer updateflow(Map<String, String> map) throws Exception {
        String uuid = map.get("uuid");
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("uuid", uuid);
        Map<String, String> map1 = technicalAdviceMapper.serverQueryLine(paramMap);
        String project_type = map1.get("project_type");
        if (project_type == "0") {
            paramMap.put("uuid", uuid);
        }
        return technicalAdviceMapper.updateFeedback(map);
    }

    @Override
    public Map<String, String> updateFeedback(Map<String, String> map) throws Exception {
        Map<String, String> map1 = new HashMap<>();
        //查询工程信息的状态
        List<Project> projects = reportProjectMapper.projectSelect(map);
        // 获取uuid
        String uuid = projects.get(0).getUuid();
        // 监护大纲
        Integer outlineStatus = Integer.valueOf(projects.get(0).getOutlineStatus());
        // 技审意见
        Integer flow_status = Integer.valueOf(projects.get(0).getFlowStatus());
        // 退回意见内容
        String project_feedback = map.get("opinion");
        if (outlineStatus >= 4 || flow_status >= 4) {
            map1.put("code", "500");
            map1.put("message", "待办状态有误");
            return map1;
        }
        Map<String, Object> stringIntegerMap = reportProjectMapper.saverFileNumber(uuid);
        // 更改监护档案状态
        if (outlineStatus < 4) {
            map.put("outlineStatus", "2");
            map.put("project_feedback", project_feedback);
            reportProjectMapper.updateProjectVersionStatus(map);
            Integer flow_number = Integer.valueOf(stringIntegerMap.get("flow_number").toString());
            TechnicalHistory technicalHistory = new TechnicalHistory();
            technicalHistory.setCreateTime(new Date());
            technicalHistory.setOperationalType("2");
            technicalHistory.setOperationalFlow("2");
            technicalHistory.setOperationalContext("监护大纲资料校对");
            technicalHistory.setOperationalState("1");
            technicalHistory.setOperationalProject(uuid);
            technicalHistory.setOperationalNumber(flow_number);
            technicalAdviceMapper.serverTechnicalHistory(technicalHistory);
        }
        // 更改技审意见状态
        if (flow_status < 4) {
            map.put("flowStatus", "2");
            map.put("project_feedback", project_feedback);
            reportProjectMapper.updateProjectVersionStatus(map);

            Integer flow_number = Integer.valueOf(stringIntegerMap.get("flow_number").toString());
            TechnicalHistory technicalHistory = new TechnicalHistory();
            technicalHistory.setCreateTime(new Date());
            technicalHistory.setOperationalType("1");
            technicalHistory.setOperationalFlow("2");
            technicalHistory.setOperationalContext("技审意见资料校对");
            technicalHistory.setOperationalState("1");
            technicalHistory.setOperationalProject(uuid);
            technicalHistory.setOperationalNumber(flow_number);
            technicalAdviceMapper.serverTechnicalHistory(technicalHistory);
        }
        // 得到文件id的数据
        String sendbackId = map.get("sendbackId");
        List<String> idList= Arrays.asList(sendbackId.split(","));
        Map<String, Object> idListmap = new HashMap<>();
        idListmap.put("id",idList);
        reportProjectMapper.updateBatch(idListmap);
        map1.put("code", "200");
        map1.put("message", "退回成功");
        return map1;
    }

    @Override
    public Map<String, String> serverQueryLine(Map<String, String> paramMap) {
        // 获取工程信息表中是否有工程类型
        Map<String, String> map = technicalAdviceMapper.serverQueryLine(paramMap);
        String project_type = map.get("project_type");
        Map<String, String> techninum = technicalAdviceMapper.opinionPipeline(paramMap);
        // 判断工程信息表是否有类型
        Boolean projectBoolean = project_type != "7" && project_type != "8" && project_type != "0";
        // 判断技审数据是否为空
        Boolean techninumBoolean = techninum == null || techninum.isEmpty();
        // 当工程信息表中有类型的情况下且技审表数据为空的情况下
        if (projectBoolean == true && techninumBoolean == true) {
            map.put("type", project_type);
            map.put("pipeline", "0");
            map.put("pipelinesort", "0");
            return map;
            // 当工程信息表中有类型的情况下且技审表数据为有的情况下
        } else if (projectBoolean == true && techninumBoolean == false) {
            String type = techninum.get("uploading_type");
            String pipeline = techninum.get("pipeline");
            String pipelinesort = techninum.get("pipelinesort");
            map.put("type", type);
            map.put("pipeline", pipeline);
            map.put("pipelinesort", pipelinesort);
            return map;
            // 当工程信息表中无类型的情况下且技审表数据为有的情况下
        } else if (projectBoolean == false && techninumBoolean == false) {
            String type = techninum.get("uploading_type");
            String pipeline = techninum.get("pipeline");
            String pipelinesort = techninum.get("pipelinesort");
            map.put("type", type);
            map.put("pipeline", pipeline);
            map.put("pipelinesort", pipelinesort);
            return map;
            // 当工程信息表中有类型的情况下且技审表数据为有的情况下
        } else if (projectBoolean == true && techninumBoolean == false) {
            String type = techninum.get("uploading_type");
            String pipeline = techninum.get("pipeline");
            String pipelinesort = techninum.get("pipelinesort");
            map.put("type", type);
            map.put("pipeline", pipeline);
            map.put("pipelinesort", pipelinesort);
            return map;
        }
        return map;
    }

    @Override
    public Map<String, String> opinionPipeline(Map<String, String> paramMap) {
        return technicalAdviceMapper.opinionPipeline(paramMap);
    }

    @Override
    public Map<String, Object> engineeringInformation(Map<String, String> map) {
        return technicalAdviceMapper.engineeringInformation(map);
    }

    @Override
    public Integer serverTechnicalHistory(TechnicalHistory technicalHistory) {
        return technicalAdviceMapper.serverTechnicalHistory(technicalHistory);
    }

    /**
     * 技审意见：techAuditOpinion  0:N   1:Y
     * 专项保护方案：specialProtectionPlan   0:N   1:Y
     *
     * @param uuid
     * @return
     */
    @Override
    public Map<String, String> navigationBartechAudit(String uuid) {
        Map<String, String> map = new HashMap<>();
        // 根据UUID判断是否有技审意见
        Integer a = technicalAdviceMapper.countTechnicalAdvice(uuid);
        if (a == 0) {
            map.put("techAuditOpinion", "0");
        } else {
            map.put("techAuditOpinion", "1");
        }
        // 根据UUID判断是否有专项保护方案
        Integer s = technicalAdviceMapper.countspecialProtection(uuid);
        if (s == 0) {
            map.put("specialProtectionPlan", "0");
        } else {
            map.put("specialProtectionPlan", "1");
        }
        return map;
    }

    @Override
    public Map<String, Object> queryBacklog(Map<String, String> map) throws Exception {
        Map<String, Object> total = new ArrayMap<>();
        String manager_number = map.get("managerNumber");
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        //监护大纲待办
        Map map1 = new ArrayMap();
        map1.put("manager_number", manager_number);
        map1.put("outline_exist", 1);
        map1.put("outline_status", "1,3,5,6".split(","));
        map1.put("state", "1");
        List<Map<String, String>> tm1 = technicalAdviceMapper.saverBacklog(map1);

        //技术审查（征询）待办
        Map map2 = new ArrayMap();
        map2.put("manager_number", manager_number);
        map2.put("flow_status", "1,3,5".split(","));
        map2.put("type", "1,2,3,4".split(","));
        map2.put("state", "2");
        List<Map<String, String>> tm2 = technicalAdviceMapper.saverBacklog(map2);

        //技术审查（许可）待办
        Map map3 = new ArrayMap();
        map3.put("manager_number", manager_number);
        map3.put("flow_status", "1,3,4,5".split(","));
        map3.put("type", "5".split(","));
        map3.put("state", "3");
        List<Map<String, String>> tm3 = technicalAdviceMapper.saverBacklog(map3);
        //专项保护方案待办
        Map map4 = new ArrayMap();
        map4.put("manager_number", manager_number);
        map4.put("flow_status", "7".split(","));
        map4.put("type", "5".split(","));
        map4.put("state", "4");
        List<Map<String, String>> tm4 = technicalAdviceMapper.saverBacklog(map4);
        tm1.addAll(tm2);
        tm1.addAll(tm3);
        tm1.addAll(tm4);


        //监护大纲已办
        Map map5 = new ArrayMap();
        map5.put("manager_number", manager_number);
        map5.put("outline_exist", 1);
        map5.put("outline_status", "7".split(","));
        map5.put("state", "1");
        map5.put("year", year);
        List<Map<String, String>> tm5 = technicalAdviceMapper.saverBacklog(map5);

        //技术审查（征询）已办
        Map map6 = new ArrayMap();
        map6.put("manager_number", manager_number);
        map6.put("flow_status", "7".split(","));
        map6.put("type", "1,2,3,4".split(","));
        map6.put("state", "2");
        map6.put("year", year);
        List<Map<String, String>> tm6 = technicalAdviceMapper.saverBacklog(map6);
        //技术审查（许可）已办
        Map map7 = new ArrayMap();
        map7.put("manager_number", manager_number);
        map7.put("flow_status", "7".split(","));
        map7.put("type", "5".split(","));
        map7.put("state", "3");
        map7.put("year", year);
        List<Map<String, String>> tm7 = technicalAdviceMapper.saverBacklog(map7);
        //专项保护方案已办
        Map map8 = new ArrayMap();
        map8.put("manager_number", manager_number);
        map8.put("flow_status", "9".split(","));
        map8.put("type", "5".split(","));
        map8.put("state", "4");
        map8.put("year", year);
        List<Map<String, String>> tm8 = technicalAdviceMapper.saverBacklog(map8);
        tm5.addAll(tm6);
        tm5.addAll(tm7);
        tm5.addAll(tm8);
        //待办列表
        total.put("listBacklog", tm1);
        //已办列表
        total.put("listFinish", tm5);
        // 待办总数
        total.put("sumBacklog", tm1.size());
        // 已办总数
        total.put("sumFinish", tm5.size());
        return total;
    }

    public void downtechnicalFile(String docx, String pdf) throws Exception {
        minIoUtil.removeObject("projectword", docx);
        minIoUtil.removeObject("projectpdf", pdf);
    }


}
